<template>
  <div class="dialogWrapper">
    <el-dialog :title="title" v-if="visible" :visible.sync="visible" width="800px" top="5vh" :before-close="handleClose"
      custom-class="check-dialog">
      <el-scrollbar class="scrollbar" ref="scrollbar">
        <div class="status-container">
          <template v-if="mySelectedRow.examineStatus === '审核中'">
            <div class="status1">审核中</div>
            <img :src="passing" alt="" class="img" />
          </template>
          <template v-if="mySelectedRow.examineStatus === '未通过'">
            <div class="status2">
              <div class="label">
                审核结果 <span class="result">未通过</span>
              </div>
              <div class="tips">原因：{{ mySelectedRow.examineDesc }}</div>
            </div>
            <img :src="notPass" alt="" class="img" />
          </template>
          <template v-if="mySelectedRow.examineStatus === '审核通过'">
            <div class="status3">
              <div class="label">审核结果 <span class="result">通过</span></div>
              <el-popover placement="bottom-start" popper-class="el-popover-self" trigger="hover">
                <div class="card-list" v-if="cardNoList.length">
                  <div class="item" v-for="item in cardNoList" :key="item.cardNo">
                    {{ item.cardNo }}
                  </div>
                </div>
                <!-- <div class="tips" slot="reference">查看职途卡号</div> -->
              </el-popover>
            </div>
            <img :src="pass" alt="" class="img" />
          </template>
        </div>
        <div class="form-container" ref="form-container">
          <el-form class="form" ref="form" :model="form" :rules="rules" size="small" label-width="200px"
            label-suffix="：">
            <el-form-item label="申请顾问类型" prop="consultantApplyType">
              <el-select class="select" v-model="form.consultantApplyType" placeholder="请选择申请顾问类型">
                <el-option v-for="item in consultantTypeOptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="申请人" prop="applyName">
              <el-input :disabled="true" v-model="mySelectedRow.consultantName"></el-input>
            </el-form-item>
            <el-form-item label="申请部门" prop="department">
              <el-input disabled v-model="mySelectedRow.depName"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="sex">
              <el-radio :disabled="false" v-model="mySelectedRow.sex" label="1">男</el-radio>
              <el-radio :disabled="false" v-model="mySelectedRow.sex" label="2">女</el-radio>
            </el-form-item>
            <el-form-item label="擅长方向(最多选3个)" prop="goodAtDirection">
              <el-checkbox-group v-model="form.goodAtDirection" :min="1" :max="3">
                <el-checkbox :disabled="false" v-for="item in goodAtDirections" :label="item"
                  :key="item">{{ item }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="标签(最多选3个)" prop="tag">
              <el-checkbox-group v-model="form.tag" :min="1" :max="3">
                <el-checkbox :disabled="false" v-for="item in tags" :label="item" :key="item">{{ item }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="申请理由" prop="applyReason">
              <el-input :disabled="false" placeholder="请填写申请理由" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
                v-model="form.applyReason"></el-input>
            </el-form-item>
            <el-form-item label="高频咨询话题" prop="highRateTopic">
              <div v-for="(item, index) in highRateTopics" :key="index" class="topics">
                <el-input :disabled="false" v-model="highRateTopics[index]" style="margin-bottom: 14px"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="联系方式(选填)" prop="phone">
              <el-input :disabled="false" maxlength="11" v-model="mySelectedRow.servicePhone"></el-input>
            </el-form-item>
            <el-form-item label="邮箱(选填)" prop="email">
              <el-input :disabled="false" v-model="mySelectedRow.serviceMail"></el-input>
            </el-form-item>
            <el-form-item label="从业年限" prop="workYears">
              <el-input :disabled="false" v-model="mySelectedRow.workYear"></el-input>
            </el-form-item>
            <el-form-item label="小程序上展示的职务" prop="uniappJob">
              <el-input :disabled="false" v-model="mySelectedRow.positionName"></el-input>
            </el-form-item>
            <el-form-item label="小程序上展示的服务人数" prop="serveNum">
              <el-input :disabled="false" v-model="mySelectedRow.serviceCount"></el-input>
            </el-form-item>
            <el-form-item label="上传形象照片" prop="photo">
              <img v-if="mySelectedRow.consultantPic" :src="mySelectedRow.consultantPic" class="avatar" />
            </el-form-item>
            <el-form-item label="上传企业微信个人二维码" prop="wechatQrcode">
              <img v-if="mySelectedRow.wechatQrcode" :src="mySelectedRow.wechatQrcode" class="avatar" />

            </el-form-item>
            <el-form-item label="审核人" prop="auditObj">
              <el-input :disabled="true" v-model="mySelectedRow.examineName"></el-input>
            </el-form-item>
            <el-form-item v-if="
                mySelectedRow.examineStatus === '审核中' &&
                mySelectedRow.examineOaId == cureentPersonOaId
              " label="是否通过申请" prop="passOrNot">
              <el-radio-group v-model="form.passOrNot" @change="handleChangePass">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="
                mySelectedRow.examineStatus === '审核中' && form.passOrNot == 2
              " label="不通过理由" prop="notPassReason">
              <el-input placeholder="请填写不通过理由" type="textarea" :autosize="{ minRows: 3, maxRows: 4 }"
                v-model="form.notPassReason"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <div class="operation" v-if="mySelectedRow.examineOaId == cureentPersonOaId">
        <el-button v-if="mySelectedRow.examineStatus === '审核中'" class="btn" @click="handleClose">取消</el-button>
        <el-button v-if="mySelectedRow.examineStatus === '审核中'" class="btn" type="primary" @click="confirmPassOrNot">确
          定</el-button>
      </div>
      <div class="operation" v-if="
          (mySelectedRow.examineOaId == cureentPersonOaId ||
            mySelectedRow.oaId == cureentPersonOaId) &&
          mySelectedRow.examineStatus === '未通过'
        ">
        <el-button class="btn" type="primary" @click="applyAgain">再次申请</el-button>
      </div>
    </el-dialog>
    <PersonSelect :visible.sync="personSelectVisible" width="70%" :selectedArr="selectedArr" :component="dataType"
      :multiple="false" @cancel="cancel" @confirm="selectConfirm"></PersonSelect>
  </div>
</template>

<script>
import {
  audit,
  applyCard,
  getCardNoList,
  getStockNum,
  addExamineRecord,
  applyConsultantAgain,
} from "@/api/index";
import pass from "@/assets/images/pass.png";
import passing from "@/assets/images/passing.png";
import notPass from "@/assets/images/notPass.png";
export default {
  name: "Dialog",
  components: {
    PersonSelect: () => import("@/components/PersonSelect"),
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    selectedRow: {
      type: Object,
      default: () => {},
    },
    auditerList: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      mySelectedRow: {}, // 保证单项数据流 用这个变量接收由父组件传递过来的selectedRow
      cureentPersonOaId: JSON.parse(sessionStorage.getItem("userInfo"))
        .user_source_id,
      pass,
      passing,
      notPass,
      title: "",
      stockNum: 0,
      status: 3,
      consultantTypeOptions: [
        { label: "内部职途顾问", value: 10 },
        { label: "外部职途顾问", value: 20 },
      ],
      form: {
        consultantApplyType: "",
        applyName: "",
        department: "",
        sex: "",
        goodAtDirection: [],
        tag: [],
        applyReason: "",
        phone: "",
        email: "",
        workYears: "",
        uniappJob: "",
        serveNum: "",
        auditObj: null, // 审核人
        passOrNot: "",
        notPassReason: "",
      },
      goodAtDirections: [
        "职业规划",
        "简历精修",
        "投递指导",
        "面试辅导",
        "薪酬谈判",
        "Offer筛选",
      ],
      tags: ["一览精选", "平台优选", "金牌导师"],
      appList: [],
      disabledForm: false,
      showNotPassReason: false,
      isSamePerson: false,
      rules: {
        consultantApplyType: [
          { required: true, message: "请选择申请顾问类型", trigger: "change" },
        ],
        applyName: [
          { required: true, message: "请填写申请人名称", trigger: "change" },
        ],
        department: [
          { required: true, message: "请选申请部门", trigger: "change" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "change" }],
        goodAtDirection: [
          { required: true, message: "请选择擅长方向", trigger: "change" },
        ],
        tag: [{ required: true, message: "请选择标签", trigger: "change" }],
        applyReason: [
          { required: true, message: "请填写申请理由", trigger: "change" },
        ],
        highRateTopic: [{ required: false }],
        phone: [{ required: false }],
        email: [{ required: false }],
        workYears: [
          { required: true, message: "请填写从业年限", trigger: "change" },
        ],
        uniappJob: [
          {
            required: true,
            message: "请填写小程序上展示的职务",
            trigger: "change",
          },
        ],
        serveNum: [
          {
            required: true,
            message: "请填写小程序上展示的服务人数",
            trigger: "change",
          },
        ],
        photo: [
          {
            required: true,
            message: "请上传形象照片",
            trigger: "change",
          },
        ],
        wechatQrcode: [
          {
            required: true,
            message: "请上传企业微信个人二维码",
            trigger: "change",
          },
        ],
        passOrNot: [
          {
            required: true,
            message: "请选择是否通过",
            trigger: "change",
          },
        ],
        notPassReason: [
          {
            required: true,
            message: "请填写不通过理由",
            trigger: "change",
          },
        ],
      },

      showAuditBtn: false,
      showConfirmBtn: false,
      personSelectVisible: false,
      showCardSource: false,
      loading: false,
      currentState: 0,
      selectedArr: [],
      dataType: "el-dialog",
      currentSelectApplyPersonInfo: {},
      cardNoList: [],
    };
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getCardNoListFn();
          // this.getAppList();
          this.getStockNumFn();
        }
      },
      immediate: true,
    },
    selectedRow: {
      handler(val) {
        this.title = val.consultantName + "的申请详情";
      },
      deep: true,
      immediate: true,
    },
    "form.applyState": {
      handler(val) {
        if (val == 1 || val == 0) {
          this.showNotPassReason = false;
        } else {
          this.showNotPassReason = true;
        }
      },
      immediate: true,
    },
    "form.applyType": {
      handler(val) {
        if (val == 1) {
          this.showCardSource = true;
        } else {
          this.showCardSource = false;
        }
      },
    },
  },
  created() {
    this.mySelectedRow = this.selectedRow;
    this.mySelectedRow.consultantType =
      this.mySelectedRow.consultantType == "内部职途顾问"
        ? "内部职途顾问"
        : "外部职途顾问";
    this.form.consultantApplyType =
      this.selectedRow.consultantType == "内部职途顾问" ? 10 : 20;
    this.form.goodAtDirection = this.selectedRow.goodAt.split("|");
    this.form.tag = this.selectedRow.consultantTag.split("|");
    this.highRateTopics = this.selectedRow.highTopic.split("|");
    this.form.applyReason = this.selectedRow.applyReason;
  },
  mounted() {},
  methods: {
    async addExamineRecord() {
      const params = {
        consultantId: this.selectedRow.consultantId,
        examineOaId: this.selectedRow.examineOaId,
        examineStatus: this.form.passOrNot === 1 ? 10 : 30,
        examineName: this.selectedRow.examineName,
        examineDesc: this.form.notPassReason,
      };
      const res = await addExamineRecord(params);
      if (res.code === 200) {
        this.$message.success("审核成功");
      }
    },
    confirmPassOrNot() {
      // 需要校验的字段
      let fieldsToValidate =
        this.form.passOrNot === 2
          ? ["passOrNot", "notPassReason"]
          : ["passOrNot"];
      // 将回调转换为Promise
      Promise.all(
        fieldsToValidate.map((field) => {
          return new Promise((resolve) => {
            this.$refs["form"].validateField(field, (errorMessage) => {
              resolve(errorMessage);
            });
          });
        })
      ).then((errorMessages) => {
        // errorMessages 里是各个字段的验证错误信息, 如果数组里全为空串则所有验证通过
        // 判断errorMessages 里是否全是空串
        let valid = errorMessages.every((errorMessage) => {
          return errorMessage == "";
        });

        if (valid) {
          this.$emit("update:visible", false);
          this.addExamineRecord();
        }
        this.$emit("refresh");
      });
    },
    applyAgain() {
      console.log("这里点击了再次申请");
      this.applyConsultantAgain();
    },
    async applyConsultantAgain() {
      const params = {
        examineName: this.mySelectedRow.examineName,
        examineOaId: this.mySelectedRow.examineOaId,
        goodAt: this.form.goodAtDirection.join("|"),
        applyReason: this.form.applyReason,
        consultantId: "",
        regionName: this.mySelectedRow.regionName,
        serviceMail: this.mySelectedRow.serviceMail,
        consultantTag: this.form.tag.join("|"),
        examineStatus: 20, // 审核状态 写死20 新增之后都是审核中
        consultantType: this.form.consultantApplyType,
        bday: this.mySelectedRow.bday,
        briefDesc: "",
        consultantPic: this.mySelectedRow.imageUrl,
        positiveDesc: "",
        servicePhone: this.mySelectedRow.phone,
        sex: this.mySelectedRow.sex,
        showRateScore: "",
        useStatus: 2,
        consultantName: this.mySelectedRow.consultantName,
        serviceCount: this.mySelectedRow.serveNum,
        regionId: "",
        highTopic: this.highRateTopics.join("|"),
        positionName: this.mySelectedRow.positionName,
        workYear: this.mySelectedRow.workYear,
        oaId: this.mySelectedRow.oaId,
        applyOaId: this.mySelectedRow.applyOaId,
        depId: this.mySelectedRow.depId,
        depName: this.mySelectedRow.depName,
      };
      const res = await applyConsultantAgain(params);
      if (res.code == 200) {
        console.log("res", res.code);
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
        this.$emit("update:visible", false);
        this.$emit("refresh");
      }
    },
    getStockNumFn() {
      getStockNum({}).then((res) => {
        if (res.code == 200) {
          this.stockNum = res.data;
        }
      });
    },
    getCardNoListFn() {
      const params = {
        applyId: this.selectedRow.applyId,
      };
      getCardNoList(params).then((res) => {
        if (res.code == 200 && Array.isArray(res.data)) {
          this.cardNoList = res.data;
        }
      });
    },
    handleApplyAgain() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm("请再次确认申请的事项是否正确", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.loading = true;
            const params = {
              ...this.form,
              applyReason: this.form.applyReason,
              applyNum: this.form.applyNum,
              cost: this.form.cost,
              applyAdminId: this.form.applyAdminId,
              department: this.form.department,
              applyAdminName: this.form.applyAdminName,
              receiverPhone: this.form.receiverPhone,
              receiverName: this.form.receiverName,
              receiverAddress: this.form.receiverAddress,
              applyType: this.form.applyType == 1 ? 1 : 2,
              isTest:
                this.form.applyType == 1 ? 0 : this.form.applyType == 2 ? 0 : 1,
              cardType: this.form.cardType[this.form.cardType.length - 1],
              expireTime: this.form.expireTime + " 23:59:59",
              auditAdminId: this.form.auditObj.auditAdminId,
              auditAdminName: this.form.auditObj.auditAdminName,
            };
            delete params.applyState;
            delete params.auditSuggestion;
            applyCard(params)
              .then((res) => {
                if (res.code == 200) {
                  this.$message.success("已提交申请，请等待审核");
                  const keys = Object.keys(this.form);
                  keys.forEach((key) => {
                    if (key == "auditObj") {
                      this.form[key] = null;
                    } else if (key == "rights") {
                      this.form[key] = [];
                    } else {
                      this.form[key] = "";
                    }
                  });
                  this.$nextTick(() => {
                    this.$refs.form.clearValidate();
                  });
                  this.$emit("update:visible", false);
                  this.$emit("refresh");
                }
              })
              .finally(() => {
                this.loading = false;
              });
          });
        } else {
          return false;
        }
      });
    },

    handleFocusInput() {
      this.personSelectVisible = true;
    },
    selectConfirm(e) {
      this.currentSelectApplyPersonInfo = e[0];
      this.form.applyAdminName = e[0].name;
      this.form.applyAdminId = e[0].id;
    },
    cancel() {
      this.personSelectVisible = false;
    },
    scrollToBottom(ref) {
      // 使用 ref 获取到元素
      const element = ref ? ref.value : null;
      // 判断元素是否为空，以及元素是否存在于 DOM 中
      if (element && document.contains(element)) {
        // 设置滚动条位置到底部
        element.scrollTop = element.scrollHeight;
      }
    },
    handleChangePass(val) {
      if (val == 2) {
        this.showNotPassReason = true;
        this.$nextTick(() => {
          const scrollbarRef = this.$refs.scrollbar;
          scrollbarRef.wrap.scrollTop = scrollbarRef.wrap.scrollHeight;
        });
      } else {
        this.showNotPassReason = false;
      }
    },
    checkIfNum() {
      this.form.applyNum = this.form.applyNum.toString().replace(/\D/g, "");
    },
    onSubmit() {
      // 需要校验的字段
      let fieldsToValidate = this.showNotPassReason
        ? ["applyState", "auditSuggestion"]
        : ["applyState"];

      // 将回调转换为Promise
      Promise.all(
        fieldsToValidate.map((field) => {
          return new Promise((resolve) => {
            this.$refs["form"].validateField(field, (errorMessage) => {
              resolve(errorMessage);
            });
          });
        })
      ).then((errorMessages) => {
        // errorMessages 里是各个字段的验证错误信息, 如果数组里全为空串则所有验证通过
        // 判断errorMessages 里是否全是空串
        let valid = errorMessages.every((errorMessage) => {
          return errorMessage == "";
        });

        if (valid) {
          this.loading = true;
          const params = {
            applyId: this.form.applyId,
            applyState: this.form.applyState,
            auditSuggestion: this.form.auditSuggestion,
          };
          audit(params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("审核成功");
                this.handleClose();
                this.$emit("refresh");
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    handleClose() {
      const keys = Object.keys(this.form);
      keys.forEach((key) => {
        if (key == "list") {
          this.form[key] = [];
        } else if (key == "auditObj") {
          this.form[key] = null;
        } else {
          this.form[key] = "";
        }
      });
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style>
.el-popover.el-popper.el-popover-self {
  min-width: 20px !important;
}
</style>

<style lang="scss" scoped>
.scrollbar {
  height: 82vh;
  background: url("../../../../assets/images/dialogBg.png") no-repeat;
  background-position: center top;
  background-size: 100% 22%;
}
.card-list {
  max-height: 250px;
  overflow-y: scroll;
  .item {
    padding-right: 12px;
  }
}
.status-container {
  display: flex;
  justify-content: center;
  align-items: center;
  border-bottom: 1px solid $grey-2;
  .status1 {
    font-size: 22px;
    color: #1e9ccb;
  }
  .status2 {
    .label {
      padding-bottom: 15px;
      font-size: 16px;
      color: #000;
    }
    .tips {
    }
  }
  .status3 {
    .label {
      padding-bottom: 15px;
      font-size: 16px;
      color: #000;
    }
    .result {
      font-size: 22px;
      font-weight: bold;
      color: #0cb354;
      padding-left: 15px;
    }
    .tips {
      font-size: 16px;
      color: #7052ff;
      cursor: pointer;
    }
  }
  .img {
    width: 120px;
    height: 120px;
    margin-left: 28px;
  }
}
.form-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  margin-top: 24px;
  width: 80%;
  position: relative;
  padding-bottom: 60px;
  ::v-deep .el-form-item__label {
    color: #636e95;
  }
  .left-num {
    font-size: 14px;
    color: #f44716;
  }
  .form {
    width: 100%;
    .select {
      width: 100%;
    }
    .checkbox {
      ::v-deep .el-form-item__content {
        display: flex;
      }
    }
    ::v-deep .el-tag.el-tag--info {
      margin: 0 8px 8px 0;
      color: #333;
    }
    ::v-deep .el-form-item--small.el-form-item {
      margin-bottom: 32px;
    }
  }
  ::v-deep .el-form-item__label {
    padding: 0 4px 0 0;
  }
  ::v-deep .el-input.is-disabled .el-input__inner {
    color: #333;
  }
  ::v-deep .el-textarea.is-disabled .el-textarea__inner {
    color: #333;
  }
}
::v-deep .el-dialog__header {
  padding-bottom: 20px;
}
::v-deep .el-dialog__body {
  padding: 0 !important;
}
::v-deep .el-scrollbar__wrap {
  border-top: 1px solid $grey-2;
}
.operation {
  width: 100%;
  padding: 15px 0;
  border-top: 1px solid $grey-2;
  background-color: #fff;
  display: flex;
  justify-content: center;
  position: absolute;
  bottom: 0;
  z-index: 999;
  border-radius: 8px;
  .btn {
    width: 200px;
  }
  ::v-deep .el-button--primary.is-plain,
  .el-button--primary.is-plain {
    background-color: #fff;
    border-color: $primary-color;
  }
  ::v-deep .el-button--primary.is-plain:hover,
  .el-button--primary.is-plain:focus {
    color: $primary-color;
  }
}
.avatar {
  width: 95px;
  height: 95px;
  display: block;
}
::v-deep .check-dialog {
  border-radius: 8px;
}
</style>
